<template>
  <div class="container">
    <!-- 顶部横幅 -->
    <div class="header">
      <p>专注进出口贸易数据统计分析，一站式数据查询平台</p>
    </div>

    <!-- 内容区 -->
    <div class="content-panel">
      <!-- 左侧查询表单 -->
      <div class="form-area">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="中国" name="china">
            <ChinaData
              @macro-search="macroSearch"
            />
          </el-tab-pane>

          <el-tab-pane label="全球" name="global">
            <GlobalData/>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 右上 -->
      <div class="table-area">
        <div class="table-toolbar">
          <div class="tools">
            <el-button type="text" @click="onDownload"
            >
              <el-icon>
                <Download/>
              </el-icon>
              下载
            </el-button
            >
            <el-button type="text" @click="onChart"
            >
              <el-icon>
                <DataAnalysis/>
              </el-icon>
              图表
            </el-button
            >
            <el-button type="text" @click="onAI"
            >
              <el-icon>
                <ChatLineSquare/>
              </el-icon>
              AI报告
            </el-button
            >
            <el-button type="text" @click="customReport"
            >
              <el-icon>
                <EditPen/>
              </el-icon>
              定制报告
            </el-button
            >
          </div>
        </div>

        <el-table :data="tableData" border style="width: 100%" v-loading="tableLoading">
          <el-table-column
            v-for="col in tableColumns"
            :key="col.colName"
            :prop="col.colName"
            :label="col.nameCn"
          />
        </el-table>
        <Pagination
        :total="Number(total)"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page="pageInfo.pageNum"
        :limit="pageInfo.pageSize"
      />
      </div>
    </div>

    <!-- 定制报告弹窗 -->
    <el-dialog v-model="customDialogVisible" title="定制服务" width="55%">
      <div
        style="
          text-align: center;
          padding: 10px 0 20px;
          display: flex;
          align-items: center;
          justify-content: center;
        "
      >
        <div
          style="
            display: flex;
            flex-direction: column;
            gap: 16px;
            align-items: flex-start;
          "
        >
          <!-- 左侧数字组 -->
          <div style="display: flex; align-items: center; gap: 8px">
            <div style="font-size: 40px; color: #007bba; width: 60px">01</div>
            <div>根据用户的个性化需求成立专项组</div>
          </div>
          <div style="display: flex; align-items: center; gap: 8px">
            <div style="font-size: 40px; color: #007bba; width: 60px">03</div>
            <div>专家分析及撰写报告</div>
          </div>
        </div>

        <img
          src="../assets/xwimg/center.png"
          alt="icon"
          style="width: 160px; height: 160px; margin: 0 20px"
        />

        <div
          style="
            display: flex;
            flex-direction: column;
            gap: 16px;
            align-items: flex-end;
          "
        >
          <!-- 右侧数字组 -->
          <div style="display: flex; align-items: center; gap: 8px">
            <div>制定解决方案，获取一手数据</div>
            <div style="font-size: 40px; color: #007bba; width: 60px">02</div>
          </div>
          <div style="display: flex; align-items: center; gap: 8px">
            <div>报告交付</div>
            <div style="font-size: 40px; color: #007bba; width: 60px">04</div>
          </div>
        </div>
      </div>

      <el-form :model="customForm" label-width="100px" style="padding: 0 20px">
        <el-divider content-position="left">定制报告需求</el-divider>


        <el-form-item label="需求行业">
          <el-cascader
            v-model="selectedIndustryPath"
            :options="industryOptionsList"
            :props="cascaderProps"
            placeholder="请选择行业"
            clearable
            style="width: 100%"
            @change="handleIndustryChange"
          />
        </el-form-item>


        <el-form-item label="公司名称">
          <el-input v-model="customForm.companyName" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="联系方式">
          <el-input v-model="customForm.phone" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="联系邮箱">
          <el-input v-model="customForm.email" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="详细描述">
          <el-input
            type="textarea"
            :rows="3"
            v-model="customForm.script"
            placeholder="请输入描述"
          />
        </el-form-item>

        <div
          style="
            font-size: 12px;
            color: #999;
            margin-top: 5px;
            text-align: right;
          "
        >
          * 留下需求，1-3个工作日内将由客服经理联系您
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer" style="padding: 10px">
          <el-button @click="customDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onCustomConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!--    ai对话功能-->
    <AIDialog ref="aiRef"/>
  </div>
</template>

<script setup>
import {reportApi} from '../api/report';
import AIDialog from './components/AIDialog/index.vue';
import { ref, onMounted, onBeforeUnmount } from 'vue'
import {ChatLineSquare, DataAnalysis, Download, EditPen} from '@element-plus/icons-vue';
import ChinaData from './components/ChinaData.vue';
import GlobalData from './components/GlobalData.vue';
import {QueryDataApi} from "../api/Data.js";
import {bus} from '../utils/bus.js'
const activeTab = ref('china')
const customDialogVisible = ref(false)


const tableData = ref([])
const tableLoading = ref(false)
const tableColumns = ref([])
// 分页
const pageInfo= ref({
  pageNum:1,
  pageSize:20,
})
//
const paramsData = ref({
  api:'',
  prop:''
})
onMounted(() => {
  bus.on('detail-search', onDetailSearch)
  bus.on('macro-search',macrosearch)
})
onBeforeUnmount(() => {
  bus.off('detail-search', onDetailSearch)
  bus.off('macro-search',macrosearch)
})
const onDetailSearch = ({ api, prop, params }) => {
  paramsData.value = { api, prop, params }
  Object.assign(pageInfo.value, params)
  getTableData()
}
const macrosearch=({ api, prop, params }) => {
  paramsData.value = { api, prop, params }
  Object.assign(pageInfo.value, params)
  getTableData()
}


const handleCurrentChange = (page) => {
  pageInfo.value.pageNum = page
  getTableData()
}
const handleSizeChange = (limit) => {
  pageInfo.value.pageSize = limit
  getTableData()
}
const total = ref(0)
const getTableData = async () => {
  const {api,prop} = paramsData.value
  tableLoading.value = true
  await QueryDataApi[api](pageInfo.value).then((res) => {
    if (res.code === 0) {
      const list = res.data[prop] || []
      tableData.value = list.tableList ||[]
      if(list.hasOwnProperty('title')){
        tableColumns.value = list.title
      }
      if(list.hasOwnProperty('total')){
        total.value = list.total
      }
    }
  }).finally(()=>{
    tableLoading.value = false
  })
}
// 接受传参
const macroSearch= async(data)=>{
  const {params,api,prop} = data
  paramsData.value.api = api
  paramsData.value.prop = prop
  pageInfo.value = {
    ...pageInfo.value,
    ...params,
  }
  getTableData()
}
const customForm = ref({
  industry: '',
  companyName: '',
  phone: '',
  email: '',
  script: ''
})
// 级联选择器配置
const cascaderProps = ref({
  checkStrictly: true, // 允许选择任意节点
  expandTrigger: 'hover'
})
// 存储选中的行业路径（用于级联选择器）
const selectedIndustryPath = ref([])
const industryOptionsList = ref([])
// 处理行业选择变化
const handleIndustryChange = (path) => {
  // 当用户选择时，取当前选中的节点值（可能是任意级别）
  if (path && path.length > 0) {
    customForm.value.industry = path[path.length - 1]
  } else {
    customForm.value.industry = ''
  }
}
const customReport = async () => {
  customDialogVisible.value = true
  const res = await reportApi.getIndustry()

  // 转换行业数据
  industryOptionsList.value = Object.values(res.data.industry).map(item => ({
    value: item.code,
    label: item.label,
    children: item.children
      ? Object.values(item.children).map(c => ({
        value: c.code,
        label: c.label
      }))
      : []
  }))

  // 重置行业选择
  selectedIndustryPath.value = []
  customForm.value.industry = ''
}
const onCustomConfirm = async () => {
  const formData = {
    ...customForm.value,
    // industry 已经是字符串格式
  }
  const res = await reportApi.reportCustom(formData)

  if (res.code === 0) {
    selectedIndustryPath.value = []
    customForm.value = {
      industry: '',
      companyName: '',
      phone: '',
      email: '',
      script: ''
    }
    customDialogVisible.value = false
  }

}


const onDownload = () => {
  console.log('下载')
}
const onChart = () => {
  console.log('图表')
}

// ai对话功能
const aiRef = ref(null)
const onAI = () => {
  aiRef.value.openDialog()
}

</script>

<style scoped lang="scss">
.container {
  // background: url("../assets/xwimg/dataSearchBg.png") center/cover no-repeat;
  width: 100%;
  height: 100%;
   background: linear-gradient(
    to bottom,
    rgba(240, 250, 255, 0.7) 0%,
    rgb(255, 255, 255) 100%
  );

  .header {
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: url("../assets/xwimg/dataQueryH.png") center/cover no-repeat;

    p {
      font-weight: 600;
      font-size: 40px;
      color: #004d7d;
      margin: 0;
      letter-spacing: 2px;
    }
  }
}

.content-panel {
  height: 80vh;
  width: 95%;
  max-width: 1600px;
  margin: 20px auto;
  background: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  /* 左侧表单区域 - 添加固定高度和滚动条 */
  .form-area {
   
    flex: 1 1 350px;
    max-width: 430px;
    background: #f9f9f9;
    padding: 20px;
    position: relative;


    /* 关键修改：添加固定高度和滚动条 */
    // height: calc(85vh - 40px); /* 减去padding */
    // overflow-y: auto;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;
    }

    /* 优化标签样式 */
    :deep(.el-tabs) {
      .el-tabs__header {
        margin: 0 0 15px;
      }

      .el-tabs__nav-wrap::after {
        height: 1px;
      }
    }
  }

  /* 右侧表格区域 */
  .table-area {
    flex: 3 1 700px;
    min-width: 300px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    height: calc(80vh - 40px); /* 高度与左侧一致 */
    overflow: hidden; /* 确保内部滚动 */

    /* 表格容器添加滚动 */
    .el-table {
      flex: 1;
      overflow: auto;
    }
  }

  // 中等屏幕适配（992px以下）
  @media (max-width: 992px) {
    width: 98%;
    .form-area {
      flex-basis: 100%;
      max-width: 100%;
      order: 2;
      margin-top: 20px;
      height: auto; /* 取消固定高度 */
      max-height: 50vh; /* 添加最大高度 */
    }
    .table-area {
      flex-basis: 100%;
      order: 1;
      height: auto; /* 取消固定高度 */
    }
  }

  // 移动端适配（768px以下）
  @media (max-width: 768px) {
    border-radius: 4px;
    .form-area, .table-area {
      padding: 15px;
    }
  }

  // 小屏幕适配（480px以下）
  @media (max-width: 480px) {
    margin: 10px auto;
    .form-area, .table-area {
      padding: 10px;
    }
  }
}

// 标题优化
.header {
  p {
    font-size: 2rem;
    @media (max-width: 768px) {
      font-size: 1.5rem;
      padding: 0 10px;
      text-align: center;
    }
  }
}

// 表单元素适配 - 添加紧凑布局
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 14px; /* 减小间距 */
  }

  :deep(.el-form-item__label) {
    padding-bottom: 4px; /* 标签紧凑 */
  }

  :deep(.el-select),
  :deep(.el-input) {
    width: 100%;
  }

  .date-pickers {
    gap: 0.8rem;
  }

  /* 折叠面板内部优化 */
  :deep(.el-collapse-item) {
    .el-collapse-item__header {
      padding: 0 16px;
      height: 48px;
      font-size: 15px;
    }

    .el-collapse-item__content {
      padding: 16px;
    }
  }
}

// 工具栏优化
.table-toolbar {
  margin-bottom: 12px;

  .tools {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .el-button {
      margin-left: 0;
      padding: 7px 10px;
      font-size: 13px;
    }
  }
}
</style>
